package cn.net.wanji.utils;

import cn.hutool.core.date.DateUtil;
import cn.net.wanji.config.ApplicationConfig;
import cn.net.wanji.entity.FileCount;
import cn.net.wanji.entity.SaveFailInfo;
import cn.net.wanji.mapper.FileCountMapper;
import cn.net.wanji.service.DataCopyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author guodejun
 * @createTime 2022/10/28 10:32
 * @description
 */
@Component
public class SaveFileUtils {

    @Value("${data-copy.is-master}")
    private boolean dataCopyIsMaster;

    @Resource
    private DataCopyService dataCopyService;

    @Resource
    private FileCountMapper fileCountMapper;

    @Resource
    ApplicationConfig applicationConfig;

    static Logger log = LoggerFactory.getLogger("SaveFileUtils");

    //    @Async("doSomethingExecutor")
    public void saveFile(byte[] bytes, Integer fileType, String fileName) {
        if (fileType == 4) {
            fileName += ".mp4";
        } else {
            fileName += ".jpeg";
        }
        File file = new File(fileName);
        try {
            FileOutputStream imageOutput = new FileOutputStream(file);
            imageOutput.write(bytes, 0, bytes.length);
            imageOutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.warn("saveFile: " + fileName);
    }

    @Async("doSomethingExecutor")
    public void saveFile(List<SaveFailInfo> saveFailInfos, Integer[] fileTypes, String fileSavePath, String recordId,String time) {
        String strFormatYyyyMmddHHMmSs = DateUtils.getStrFormatYyyyMmddHHMmSs(time);
        long l = System.currentTimeMillis();

//        String time = DateUtil.parse(recordId.substring(19, 33)).toString();
        String file1 = "0";
        String file2 = "0";
        String file3 = "0";
        String file4 = "0";
        String file5 = "0";
        String file6 = "0";

        // 文件夹是否存在
        dirIsExist(fileSavePath);
        List<File> files = new ArrayList<>();
        for (SaveFailInfo saveFailInfo : saveFailInfos) {
            Integer fileType = saveFailInfo.getFileType();
            switch (fileType) {
                case 0: file1 = "1"; break;
                case 1: file2 = "1"; break;
                case 2: file3 = "1"; break;
                case 3: file4 = "1"; break;
                case 4: file5 = "1"; break;
                case 5: file6 = "1";
            }
            String fileName = saveFailInfo.getFileName();
            byte[] bytes = saveFailInfo.getBytes();
            if (fileType == 4) {
                fileName += ".mp4";
            } else {
                fileName += ".jpeg";
            }
            File file = new File(fileName);
            try {
                FileOutputStream imageOutput = new FileOutputStream(file);
                imageOutput.write(bytes, 0, bytes.length);
                imageOutput.close();
                files.add(file);
            } catch (IOException e) {
                LogUtils.errorLog(e);
                e.printStackTrace();
            }
            log.warn("saveFile: " + fileName);
        }
        long l2 = System.currentTimeMillis();

        // 数据同步
        if (dataCopyIsMaster) {
            dataCopyService.saveFile(files, fileTypes, recordId);
        }

        // 记录资源缺失情况
        fileCountMapper.insertFileCount(new FileCount(recordId, strFormatYyyyMmddHHMmSs, file1, file2, file3, file4, file5,file6));

        // 获取磁盘所剩空间
        List<String> shell = applicationConfig.getShell();
        String diskInfo = "";
        if (shell.size() != 0 && "centos".equals(applicationConfig.getSystemType())) {
            diskInfo = ShellUtils.executeNewFlow(shell);
        }
        log.warn("recordId:" + recordId + " fileCount:" + saveFailInfos.size() + " save time:" + (l2 - l) + " disk info:" + diskInfo);

    }


    public static void dirIsExist(String path) {
        File file = new File(path);
        try {
            if (!file.exists() && !file.isDirectory()) {
                boolean mkdirs = file.mkdirs();
                log.warn("创建文件夹: " + path + " " + mkdirs);
            }
        } catch (Exception e) {
            // 捕获SecurityException异常
            log.error("无法创建文件夹: " + path, e);
            // 这里可以选择抛出异常或者做其他的处理
        }
    }


}
